;
$("#goods_type").change(function () {
    addAttributeByType(this);
    addSpecByType(this);
});

function goodsTypeInit(obj) {

    addAttributeByType(obj);
    addSpecByType(obj);
}

function addAttribute() {
    $("#shop-attr").children('tbody').append(getAttributeItem(0,''));
    removeAttribute();//绑定事件
}

function removeAttribute() {
    $('#shop-attr').find('.attr-delete').each(function () {
        $(this).off('click').on('click',function () {
            $(this).parents('tr').empty();
        });
    });
}

function addAttributeByType(obj) {
    var goodTypeId = $(obj).children('option:selected').val();
    var params = $(obj).data('params');
    if(params==undefined||params == ''){
        return false;
    }
    $.ajax({
        type: 'get',
        url: params.attrUrl,
        dataType: 'json',
        data: {"goods_type":goodTypeId}
    }).done(function (response) {
        if(response.length >0){
            var  elem = '';
            $.each(response,function (i,n) {
                if($("#shop-attr").has('input[name^="attr_title"][value="'+n.title+'"]').length<1){
                    elem += getAttributeItem(n.id,n.title);
                }
            });
            $("#shop-attr").children('tbody').append(elem);
            removeAttribute();//绑定事件
        }else{
            $("#shop-attr").children('tbody').empty();
        }
    });
}

function getAttributeItem(id,title) {
    var elemAttr = '<tr>' +
        '                    <td><input class="form-control" name="attr_title[]" value="{%title%}"><input type="hidden" name="attr_id[]" value="{%id%}"></td>' +
        '                    <td>' +
        '                        <div class="d-inline-flex flex-row col-sm-10 col-md-8 col-lg-6">' +
        '                        <input class="form-control mr-2 flex-grow-1" name="attr_value[]" value="">' +
        '                        <span class="hcl hcl-circle-jian text-danger align-self-center attr-delete" style="font-size: 25px;cursor: pointer;"></span>\n' +
        '                        </div>' +
        '                    </td>' +
        '                </tr>';
    elemAttr = elemAttr.replace('{%id%}',id);
    return elemAttr.replace('{%title%}',title);
}

/**
 * @title 添加规格
 */
function addSpec() {
    layer.prompt({title: '请输入规格名称，并确认'}, function(spec_title, index){
        layer.close(index);
        layer.prompt({title: '请如何规格值,多个值用逗号分隔，并确认', formType: 2}, function(text, index){
            layer.close(index);
            var item = {"id":uuid(),"title":spec_title,"value":text};
            $("#shop-spec").append(getSpecColumn(item));
            specBindEvent();
        });
    });
}

/**
 * @tite 添加规格值
 * @param id
 */
function addSpecValue(id) {
    layer.prompt({title: '请输入规格名称，并确认'}, function(value, index){
        layer.close(index);
        $("#shop-spec-"+id).find('button').before(getSpecItem(id,value));
        specBindEvent();
    });
}

function addSpecByType(obj) {
    var goodTypeId = $(obj).children('option:selected').val();
    var params = $(obj).data('params');
    var  elem = '';
    var defaultSpecs = $('#shop-spec').data('default');

    if(params==undefined||params == ''){
        return false;
    }
    $.ajax({
        type: 'get',
        url: params.specUrl,
        dataType: 'json',
        data: {"goods_type":goodTypeId}
    }).done(function (response) {
        //console.log(response);
        if(response.length >0){
            $.each(response,function (i,n) {
                elem +=getSpecColumn(n);
            });
            if (defaultSpecs != '' && defaultSpecs != undefined) {
                $.each(defaultSpecs,function (i,n) {
                    if(n.spec_id<=0){
                        n.id = uuid();
                        elem +=getSpecColumn(n);
                    }
                });
            }
            $("#shop-spec").empty().append(elem);
            $('#shop-spec-body').html(getSpecValue());
            specBindEvent();
        }else{
            $("#shop-spec").empty()
        }
    });
}

function getSpecColumn(item) {

    var elemColumn = ' <div class="form-group mb-0" id="shop-spec-'+item.id+'" data-title="'+item.title+'">' +
        '<input name="spec_title['+item.id+']" type="hidden" value="'+item.title+'"/><label style="font-size: 14px;">'+item.title+':</label>{%items%}</div>';
    var elemItem = '';
    var defaultSpecs = $('#shop-spec').data('default');
    var defaultVal = new Array();
    
    if (defaultSpecs != '' && defaultSpecs != undefined) {
        $.each(defaultSpecs,function (i) {
            var v = defaultSpecs[i];
            if(v.title == item.title){
                return defaultVal = v.value.split(',');
            }
        });
    }


    $.each(item.value.split(','),function (i,n) {
        if ($.inArray(n,defaultVal)>-1){
            elemItem  += getSpecItem(item.id,n,'checked');
        }else {
            elemItem  += getSpecItem(item.id,n,'');
        }
    });
    elemItem +="<button type='button' class='ml-2 btn btn-danger btn-xs' onclick='addSpecValue("+item.id+")'>添加值</button>";
    return elemColumn.replace('{%items%}',elemItem);
}

function getSpecItem(specId,title,defaultVal) {
    var elemItem = ' <label class="label-checkbox  mr-1 d-inline-flex align-items-center">' +
        '                            <div class="checkbox-box checkbox-box-sm checkbox-box-red">' +
        '                                <input name="spec['+specId+'][]" data-id="'+specId+'" '+defaultVal+' class="shop-spec-value" type="checkbox" value="'+title+'" />' +
        '                                <span class="hcl hcl-correct"></span>' +
        '                            </div><span class="ml-2" style="font-size: 14px;">'+title+'</span>' +
        '                        </label>';

    return elemItem;
}

function specBindEvent() {
    $('input.shop-spec-value').off('click').on('click',function () {
        $('#shop-spec-body').html(getSpecValue());
    })
}

function getSpecValue() {
    var titles = new Array();
    var specIds = new Array();
    $('input.shop-spec-value:checked').each(function (i,n) {
        var specId = $(this).data('id');
        var title = $('#shop-spec-'+specId).data('title');
        if($.inArray(title,titles)==-1){
            titles.push(title);
            specIds.push(specId);
        }
    });
    var spec = new Array();
   $.each(specIds,function (i,n) {
       var specItem = [];
       $('#shop-spec-'+n).find('input.shop-spec-value:checked').each(function () {
           specItem.push($(this).val())
       })
       spec[i]=specItem;
   })
   return addSpecTable(titles,doCombination(spec));
}

function addSpecTable(titles,arr) {
    var table ='<table class="table table-bordered info-card " id="shop-spec-value">' +
        '                <thead><tr class="table-secondary">{%td%}<td>销售价格<button class="float-right btn btn-xs btn-danger" type="button" onclick="addOneValue(\'price\')">统一值</button></td>' +
        '                   <td>会员价格<button class="float-right btn btn-xs btn-danger" type="button" onclick="addOneValue(\'vip_price\')">统一值</button></td>' +
        '                   <td>市场价格<button class="float-right btn btn-xs btn-danger" type="button" onclick="addOneValue(\'market_price\')">统一值</button></td>' +
        '                   <td>库存<button class="float-right btn btn-xs btn-danger" type="button" onclick="addOneValue(\'stock\')">统一值</button></td></tr></thead>' +
        '                <tbody>{%tr%}</tbody>' +
        '            </table>'
    var td ='';
    for (index in titles){
        td +='<td>'+titles[index]+'</td>';
    }
    var defaultSku = $('#shop-spec').data('sku');
    var tr = '';
    for (index in arr){
        tr += '<tr>';
        for (i in arr[index]){
            tr += "<td>"+arr[index][i]+"</td>";
        }
        var defaultStock = 0, defaultPrice = 0,defaultVipPrice=0,defaultMarketPrice=0;
        $.each(defaultSku,function (i) {
            var v = defaultSku[i];
            if(v.goods_spec_items == arr[index].join(',')){
                defaultStock = v.stock;
                defaultPrice = v.price;
                defaultVipPrice = v.vip_price;
                defaultMarketPrice = v.market_price;
                return true;
            }
        })
        tr += '<td><input type="hidden" name="goods_spec[]" value="'+arr[index].join(',')+'">' +
            '<input class="form-control" name="goods_spec_price[]" value="'+defaultPrice+'"></td>' +
            '<td><input class="form-control" name="goods_spec_vip_price[]" value="'+defaultVipPrice+'"></td>' +
            '<td><input class="form-control" name="goods_spec_market_price[]" value="'+defaultMarketPrice+'"></td>' +
            '<td><input class="form-control" name="goods_spec_stock[]" value="'+defaultStock+'"></td></tr>';
    }
    table = table.replace('{%td%}',td);
    return table.replace('{%tr%}',tr)
}

function addOneValue(suffix) {
    layer.prompt({title: '请输入，并确认'}, function(value, index){
        layer.close(index);
        $('input[name^="goods_spec_'+suffix+'"]').val(value);
    });
}

/*数组排列组合*/
function doCombination(arr) {
    var count = arr.length - 1; //数组长度(从0开始)
    var tmp = [];
    var totalArr = [];// 总数组

    return doCombinationCallback(arr, 0);//从第一个开始
    //js 没有静态数据，为了避免和外部数据混淆，需要使用闭包的形式
    function doCombinationCallback(arr, curr_index) {
        for(val in arr[curr_index]) {
            tmp[curr_index] = arr[curr_index][val];//以curr_index为索引，加入数组
            //当前循环下标小于数组总长度，则需要继续调用方法
            if(curr_index < count) {
                doCombinationCallback(arr, curr_index + 1);//继续调用
            }else{
                totalArr.push(tmp);//(直接给push进去，push进去的不是值，而是值的地址)
            }

            //js  对象都是 地址引用(引用关系)，每次都需要重新初始化，否则 totalArr的数据都会是最后一次的 tmp 数据；
            oldTmp = tmp;
            tmp = [];
            for(index in oldTmp) {
                tmp.push(oldTmp[index]);
            }
        }
        return totalArr;
    }
}

function uuid() {
   var mydate = new Date();
   return  "spec"+mydate.getDay()
    + mydate.getHours()+ mydate.getMinutes()+mydate.getSeconds()+mydate.getMilliseconds()+ Math.round(Math.random() * 10000);
}